package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.Announcement;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AnnouncementService;
import com.xuanzheng.company.service.impl.AnnouncementServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/manage-announcement")
public class ManageAnnouncementServlet extends HttpServlet {
    
    private final AnnouncementService announcementService = new AnnouncementServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 添加新公告
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前用户
            HttpSession session = req.getSession();
            User currentUser = (User) session.getAttribute("user");
            
            System.out.println("当前用户: " + (currentUser != null ? currentUser.getId() + ", " + currentUser.getName() : "null"));
            
            if (currentUser == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
                out.print(gson.toJson(result));
                return;
            }
            
            System.out.println("用户角色: " + currentUser.getRole());
            System.out.println("用户公司ID: " + currentUser.getCompanyId());
            
            // 检查用户是否是公司负责人
            if (currentUser.getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有公司负责人才能管理公告");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查用户是否有公司ID
            if (currentUser.getCompanyId() == null || currentUser.getCompanyId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "您的账号未关联公司，无法发布公告");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取请求体
            StringBuilder sb = new StringBuilder();
            String line;
            try (BufferedReader reader = req.getReader()) {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
            
            System.out.println("接收到的请求体: " + sb.toString());
            
            try {
                JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
                
                // 检查JSON字段是否存在
                if (!jsonObject.has("title") || !jsonObject.has("content")) {
                    result.put("success", false);
                    result.put("message", "请求格式错误，缺少必要字段");
                    out.print(gson.toJson(result));
                    return;
                }
                
                String title = jsonObject.get("title").getAsString();
                String content = jsonObject.get("content").getAsString();
                
                // 打印接收到的数据，用于调试
                System.out.println("POST - 接收到的标题: '" + title + "'");
                System.out.println("POST - 接收到的内容: '" + content + "'");
                
                if (title == null || title.trim().isEmpty() || content == null || content.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "标题和内容不能为空");
                    out.print(gson.toJson(result));
                    return;
                }
                
                // 创建公告对象
                Announcement announcement = new Announcement();
                announcement.setTitle(title.trim());
                announcement.setContent(content.trim());
                announcement.setCompanyId(currentUser.getCompanyId());
                announcement.setPublisherId(currentUser.getId());
                announcement.setPublisherName(currentUser.getName());
                
                System.out.println("准备添加公告: " + announcement.getId() + ", " + announcement.getTitle());
                
                // 添加公告
                boolean success = announcementService.addAnnouncement(announcement);
                System.out.println("添加公告结果: " + success);
                
                if (success) {
                    result.put("success", true);
                    result.put("message", "添加公告成功");
                    result.put("data", announcement);
                } else {
                    result.put("success", false);
                    result.put("message", "添加公告失败");
                }
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "添加公告失败: " + e.getMessage());
                System.out.println("添加公告异常: " + e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
            System.out.println("服务器异常: " + e.getMessage());
            e.printStackTrace();
        }
        
        String jsonResult = gson.toJson(result);
        System.out.println("响应结果: " + jsonResult);
        out.print(jsonResult);
    }
    
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 更新公告
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前用户
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        if (currentUser == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 检查用户是否是公司负责人
        if (currentUser.getRole() != 1) {
            result.put("success", false);
            result.put("message", "只有公司负责人才能管理公告");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取请求体
        StringBuilder sb = new StringBuilder();
        String line;
        try (BufferedReader reader = req.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        
        try {
            JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
            
            // 检查JSON字段是否存在
            if (!jsonObject.has("id") || !jsonObject.has("title") || !jsonObject.has("content")) {
                result.put("success", false);
                result.put("message", "请求格式错误，缺少必要字段");
                out.print(gson.toJson(result));
                return;
            }
            
            String id = jsonObject.get("id").getAsString();
            String title = jsonObject.get("title").getAsString();
            String content = jsonObject.get("content").getAsString();
            
            // 打印接收到的数据，用于调试
            System.out.println("接收到的ID: '" + id + "'");
            System.out.println("接收到的标题: '" + title + "'");
            System.out.println("接收到的内容: '" + content + "'");
            
            if (id == null || id.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "公告ID不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            if (title == null || title.trim().isEmpty() || content == null || content.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "标题和内容不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取原公告
            Announcement announcement = announcementService.getAnnouncementById(id);
            if (announcement == null) {
                result.put("success", false);
                result.put("message", "公告不存在");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查是否是同一公司
            if (!announcement.getCompanyId().equals(currentUser.getCompanyId())) {
                result.put("success", false);
                result.put("message", "无权修改其他公司的公告");
                out.print(gson.toJson(result));
                return;
            }
            
            // 更新公告内容
            announcement.setTitle(title.trim());
            announcement.setContent(content.trim());
            
            boolean success = announcementService.updateAnnouncement(announcement);
            if (success) {
                result.put("success", true);
                result.put("message", "更新公告成功");
                result.put("data", announcement);
            } else {
                result.put("success", false);
                result.put("message", "更新公告失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新公告失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        out.print(gson.toJson(result));
    }
    
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 删除公告
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前用户
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        if (currentUser == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 检查用户是否是公司负责人
        if (currentUser.getRole() != 1) {
            result.put("success", false);
            result.put("message", "只有公司负责人才能管理公告");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取公告ID
        String id = req.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "公告ID不能为空");
            out.print(gson.toJson(result));
            return;
        }
        
        try {
            // 获取原公告
            Announcement announcement = announcementService.getAnnouncementById(id);
            if (announcement == null) {
                result.put("success", false);
                result.put("message", "公告不存在");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查是否是同一公司
            if (!announcement.getCompanyId().equals(currentUser.getCompanyId())) {
                result.put("success", false);
                result.put("message", "无权删除其他公司的公告");
                out.print(gson.toJson(result));
                return;
            }
            
            boolean success = announcementService.deleteAnnouncement(id);
            if (success) {
                result.put("success", true);
                result.put("message", "删除公告成功");
            } else {
                result.put("success", false);
                result.put("message", "删除公告失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除公告失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        out.print(gson.toJson(result));
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取单个公告详情
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前用户
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        if (currentUser == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取公告ID
        String id = req.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "公告ID不能为空");
            out.print(gson.toJson(result));
            return;
        }
        
        try {
            Announcement announcement = announcementService.getAnnouncementById(id);
            if (announcement == null) {
                result.put("success", false);
                result.put("message", "公告不存在");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查用户是否有权限查看该公告（是否属于同一公司）
            if (!announcement.getCompanyId().equals(currentUser.getCompanyId())) {
                result.put("success", false);
                result.put("message", "无权查看其他公司的公告");
                out.print(gson.toJson(result));
                return;
            }
            
            result.put("success", true);
            result.put("data", announcement);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取公告失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        out.print(gson.toJson(result));
    }
} 